import React, { FormEvent } from "react";
import { useAuth } from "context/auth-context";
import { Form, Input, Button } from "antd";
import { LongButton } from "unauthenticated-app";
import { useAsync } from "utils/use-async";

const apiUrl = process.env.REACT_APP_API_URL;
export const LoginScreen = ({
  onError,
}: {
  onError: (error: Error) => void;
}) => {
  const { login, user } = useAuth(); //不论在哪个组件调用useAuth，都可以获取用户信息

  const { run, isLoading } = useAsync(undefined, { throwOnError: true });
  const handleSubmit = async (values: {
    username: string;
    password: string;
  }) => {
    console.log("登录信息", values);
    //await run(login(values))
    //if(error) {
    //   onError(error)
    // }
    //不用以上写法捕捉异常的原因是：run方法是异步的，useAsync返回的error不等run执行完成，只能拿到null
    //必须由run方法抛出一个异常
    await run(login(values)).catch((e) => {
      onError(e);
    });
  };
  return (
    <Form onFinish={handleSubmit}>
      <Form.Item
        name={"username"}
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <Input placeholder={"用户名"} type="text" id={"username"}></Input>
      </Form.Item>
      <Form.Item
        name={"password"}
        rules={[{ required: true, message: "请输入密码" }]}
      >
        <Input placeholder={"登录密码"} type="password" id={"password"}></Input>
      </Form.Item>
      <Form.Item>
        <LongButton loading={isLoading} type="primary" htmlType={"submit"}>
          快速登录
        </LongButton>
      </Form.Item>
    </Form>
  );
};
